const {ipcRenderer} = require('electron');
const {$, convertDuration} = require('./helper');

$('addMusicBtn').addEventListener('click', e => {
  ipcRenderer.send('add-music-window');
});

const musicAudio = new Audio();
let allTracks;
let currentTrack;

const renderListHTML = (tracks) => {
  const trackList = $('trackList');
  const tracksListHTML = tracks.reduce((curr, prev) => {
    curr += `
    <li class="music-track list-group-item d-flex justify-content-between align-items-center">
      <div class="col-10">
        <i class="fas fa-music mr-2 text-secondary"></i>
        <b>${prev.fileName}</b>
      </div>
      <div class="col-2">
        <i class="fas fa-play mr-4" data-id="${prev.id}"></i>
        <i class="fas fa-trash-alt" data-id="${prev.id}"></i>
      </div>
    </li>`;
    return curr;
  }, '');
  const emptyTrackHTML = `<div class="alert alter-primary">还没有添加音乐</div>`;

  trackList.innerHTML = tracks.length ? `<ul class="list-group">${tracksListHTML}</ul>` : emptyTrackHTML;
};

const renderPlayerHTML = (name, duration) => {
  const player = $('player-status');
  const html = `
<div class="col font-weight-bold">
  正在播放: ${name}
</div>
<div class="col">
  <span id="current-seeker">00:00</span> / ${convertDuration(duration)}
</div>  
  `;
  player.innerHTML = html;
};

const updateProgressHTML = (currentTime, duration) => {
  const progress = Math.floor(currentTime / duration * 100);
  console.log(progress);
  const bar = $('player-progress');
  bar.innerHTML = progress + '%';
  bar.style.width = progress + '%';
  const seeker = $('current-seeker');
  seeker.innerHTML = convertDuration(currentTime);
};

ipcRenderer.on('getTracks', (event, tracks) => {
  renderListHTML(tracks);
  allTracks = tracks;
});

$('trackList').addEventListener('click', event => {
  event.preventDefault();
  const {dataset, classList} = event.target;
  const id = dataset && dataset.id;
  if (id && classList.contains('fa-play')) {
    if (currentTrack && currentTrack.id === id) {
      musicAudio.play();
    } else {
      currentTrack = allTracks.find(track => track.id === id);
      musicAudio.src = currentTrack.path;
      musicAudio.play();
      const resetIconElement = document.querySelector('.fa-pause');
      if (resetIconElement) {
        resetIconElement.classList.replace('fa-pause', 'fa-play');
      }
    }
    classList.replace('fa-play', 'fa-pause');
  } else if (id && classList.contains('fa-pause')) {
    musicAudio.pause();
    classList.replace('fa-pause', 'fa-play');
  } else if (id && classList.contains('fa-trash-alt')) {
    console.log(id);
    ipcRenderer.send('delete-track', id);
  }
});

// 渲染播放器状态
musicAudio.addEventListener('loadedmetadata', () => {
  renderPlayerHTML(currentTrack.fileName, musicAudio.duration);
});

// 更新播放器状态
musicAudio.addEventListener('timeupdate', () => {
  updateProgressHTML(musicAudio.currentTime, musicAudio.duration);
});
